<!DOCTYPE html>
<html lang="en-us">
<head>
  <meta charset="utf-8">
  <title>拉黑用户界面</title>
  <script src="js/vue.js"></script>
  <script src="./js/axios.js"></script>

  <!-- mobile responsive meta -->
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <meta name="description" content="Admin Page for Article Review">
  
  <!-- plugins -->
  <link rel="stylesheet" href="plugins/bootstrap/bootstrap.min.css">
  <link rel="stylesheet" href="plugins/themify-icons/themify-icons.css">
  
  <!-- Main Stylesheet -->
  <link rel="stylesheet" href="css/style.css" media="screen">

  <!-- Favicon -->
  <link rel="shortcut icon" href="images/favicon.png" type="image/x-icon">
  <link rel="icon" href="images/favicon.png" type="image/x-icon">
</head>
<body>

<!-- Navigation -->
<header class="navigation">
    <div class="container" id="index">
      <nav class="navbar navbar-expand-lg navbar-white">
        <a class="navbar-brand order-1" href="index.html">
          <img class="img-fluid" width="50px" src="images/图标.png"
            alt="中国传统文化论坛">
        </a>
        <div class="collapse navbar-collapse text-center order-lg-2 order-3" id="navigation">
          <ul class="navbar-nav mx-auto">
            <li class="nav-item active">
              <a class="nav-link" href="index.html">首页</a>
            </li>
            <li class="nav-item @@about__active">
              <a class="nav-link" href="BBS_index.html">论坛</a>
            </li>
            <li class="nav-item @@services__active">
              <a class="nav-link" href="chat.html">消息</a>
            </li>
            <li class="nav-item @@services__active">
              <a class="nav-link" href="shop.html">商店</a>
            </li>
          </ul>
        </div>
        <div class="order-2 order-lg-3 d-flex align-items-center">
          <form @submit.prevent="performSearch"> <!-- 阻止表单提交 -->
            <input 
              id="search-query" 
              name="s" 
              type="search" 
              placeholder="输入文章ID"
              v-model="searchId" 
            >
            <button type="submit" class="btn btn-search">搜索</button>
          </form>
          <button class="navbar-toggler border-0 order-1" type="button" data-toggle="collapse" data-target="#navigation">
            <i class="ti-menu"></i>
          </button>
          <ul class="navbar-nav ml-auto" v-if="userid==null">
            <li class="nav-item @@login__active">
                <a class="nav-link" href="Login.html">登录</a>
            </li>
            <li class="nav-item @@register__active">
                <a class="nav-link" href="register.html">注册</a>
            </li>
        </ul>
        <ul class="navbar-nav ml-auto 1ogined" v-else>
            <li class="nav-item @@login__active">
              <span><a class="nav-link" href="person-post.html">{{userid}}</a></span>
            </li>
            <li class="nav-item @@register__active">
                <span v-on:click.prevent="logout"><a class="nav-link" href="BBS_index.html">注销</a></span>
            </li>
        </ul>
        </div>
      </nav>
    </div>
  </header>
    <!--/MENU-JS-->
    <script>
        new Vue({
          el: "#index",
          data: {
            userid: localStorage["userid"],
            searchId: '' // 用于存储搜索的ID
          },
          methods: {
            logout: function() {
              localStorage.clear();
              this.userid = null;
            },
            performSearch: function() {
              if (!this.searchId || this.searchId.trim() === '') {
                // 如果为空，跳转到404页面
                alert("请输入文章id");
                return;
              }
              // 存储搜索ID到localStorage
              localStorage.setItem("num", this.searchId);
              // 跳转到post.html
              location.href = "post.html";
            }
          }
        })
    </script>
<!-- /navigation -->
<section class="section-ad">
    <div class="container" id="userManagement">
      <h2 class="h3 section-title">用户拉黑管理</h2>
      <div class="row">
        <div class="col-md-12">
          <table class="table table-striped">
            <thead>
              <tr>
                <th>用户ID</th>
                <th>账号状态</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="user in paginatedList" :key="user.id">
                <td>{{ user.id }}</td>
                <td>{{ user.isBlocked ? '已拉黑' : '正常' }}</td>
                <td>
                  <button 
                    class="btn" 
                    :class="user.isBlocked ? 'btn-success' : 'btn-danger'"
                    @click="toggleUserBlock(user.id, user.isBlocked)">
                    {{ user.isBlocked ? '取消拉黑' : '拉黑用户' }}
                  </button>
                </td>
              </tr>
            </tbody>
          </table>
          <nav aria-label="Page navigation" class="mt-4">
            <ul class="pagination justify-content-center">
              <li class="page-item" :class="{ disabled: currentPage === 1 }">
                <a class="page-link" href="#" @click.prevent="changePage(currentPage - 1)">
                  上
                </a>
              </li>
              <li class="page-item" v-for="page in totalPages" :key="page" 
                  :class="{ active: page === currentPage }">
                <a class="page-link" href="#" @click.prevent="changePage(page)">
                  {{ page }}
                </a>
              </li>
              <li class="page-item" :class="{ disabled: currentPage === totalPages }">
                <a class="page-link" href="#" @click.prevent="changePage(currentPage + 1)">
                  下
                </a>
              </li>
            </ul>
          </nav>
        </div>
      </div>
    </div>
  </section>
  <script>
  var vm = new Vue({
    el: "#userManagement",
    data: {
        userid: localStorage["userid"],
        userList: [],
        currentPage: 1,
        itemsPerPage: 5,
    },
    computed: {
        // 计算总页数
        totalPages() {
          return Math.ceil(this.userList.length / this.itemsPerPage)
        },
        // 当前页显示的文章列表
        paginatedList() {
          const start = (this.currentPage - 1) * this.itemsPerPage
          const end = start + this.itemsPerPage
          return this.userList.slice(start, end)
        }
      },
    mounted() {
        this.getAllUsers();
    },
    methods: {
        // 切换页码
        changePage(page) {
            if (page >= 1 && page <= this.totalPages) {
              this.currentPage = page
              // Scroll to the specific section
              const section = document.getElementById('userManagement');
              if (section) {
                section.scrollIntoView({ behavior: 'smooth' });
              }
            }
          },
          getAllUsers() {
            const currentUser = localStorage["userid"];
            axios.post("https://localhost:7071/api/Admin/getAllUsers")
            .then((res) => {
                // 过滤掉当前登录用户，并对用户按id进行排序
                const users = res.data.filter(user => String(user.id) !== String(currentUser)); // 将id转换为字符串进行比较
                users.sort((a, b) => Number(a.id) - Number(b.id));

                // 遍历排序后的用户列表，检查是否已被拉黑
                users.forEach(user => {
                    // 请求检查是否已拉黑
                    axios.get(`https://localhost:7071/api/Message/isBlocked/${currentUser}/${user.id}`)
                        .then((response) => {
                            // 根据返回的布尔值设置用户是否被拉黑
                            user.isBlocked = response.data; // true 表示已拉黑，false 表示正常
                            this.userList.push(user); // 将用户添加到列表中
                        })
                        .catch((error) => {
                            console.error("检查用户拉黑状态失败:", error);
                        });
                });
        })
        .catch((error) => {
            console.error("获取用户列表失败:", error);
        });
        },
        toggleUserBlock(userId, currentStatus) {
            const currentUser = localStorage["userid"];
            // 根据当前状态选择不同的API端点
            const url = currentStatus 
                ? `https://localhost:7071/api/Message/unblock?userId=${currentUser}&blockedUserId=${userId}`
                : `https://localhost:7071/api/Message/block?userId=${currentUser}&blockedUserId=${userId}`;
                
            axios.post(url)
                .then((response) => {
                    const user = this.userList.find(u => u.id === userId);
                    if (user) {
                        user.isBlocked = !currentStatus;
                    }
                    alert(currentStatus ? '取消拉黑成功' : '拉黑用户成功');
                })
                .catch((error) => {
                    console.error("操作失败:", error);
                    alert("操作失败，请重试");
                });
        }
    }
});
</script>
<footer class="footer">
  <div class="container">
    <div class="row align-items-center">
      <div class="col-md-5 text-center text-md-left mb-4">
        <ul class="list-inline footer-list mb-0">
          <li class="list-inline-item"><a href="privacy-policy.html">Privacy Policy</a></li>
        </ul>
      </div>
      <div class="col-md-2 text-center mb-4">
        <a href="index.html"><img class="img-fluid" width="100px" src="images/图标.png" alt="管理后台"></a>
      </div>
    </div>
  </div>
</footer>

<!-- JS Plugins -->
<script src="plugins/jQuery/jquery.min.js"></script>
<script src="plugins/bootstrap/bootstrap.js"></script>

</body>
</html>
